package com.wxmp.core.qrcode;
/**
 * 
 */

import java.awt.image.BufferedImage;
import java.io.File; 
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.wxmp.core.util.StringUtil;
import com.wxmp.core.util.UtilDateTime;
import com.wxmp.wxapi.ctrl.WxApiCtrl; 

/**
 * @author zxm
 *
 */
public class QRCodeMain{
    
    private static Logger logger = LogManager.getLogger(WxApiCtrl.class);
    
	private static void encode() {
		CodeCreator creator = new CodeCreator();
		CodeModel info = new CodeModel();
		info.setWidth(400);
		info.setHeight(400);
		info.setFontSize(24); 
		info.setContents("测试");
		info.setLogoFile(new File("/Users/java/logo.jpeg"));
		info.setDesc("我是一页孤舟");
		//info.setLogoDesc("一叶浮萍归大海，adsasfbhtjg人生何处不相逢");
		//info.setLogoDesc("一叶浮萍");
		creator.createCodeImage(info, "/Users/java/test." + info.getFormat());
	}
	
	static public void decode(InputStream input){
		CodeDecoder decoder = new CodeDecoder();
		String result = decoder.decode(input);
		System.out.println(result);
	}
	
	public static void main(String[] args) throws Exception{
		encode();
		//decode(new FileInputStream(new File("D:/2Dcode/dest.gif")));
	}

    public boolean createQRCodeByUser(String templateFile,String qrCodeFile,String headImgUrl,String nickName,JSONObject json,String outFile ) {
        boolean result = false;
        long startTime = UtilDateTime.countStart("*************************创建用户海报图片处理开始*************************");
        try{  
            BufferedImage templateImage = ImageIO.read(new File(templateFile));
            BufferedImage qrCodeImage = ImageIO.read(new File(qrCodeFile));
            BufferedImage head = this.getUserHeaderImage(headImgUrl, 132);
            result = this.createUserPoster(templateImage, qrCodeImage, head, nickName, json, outFile);
        }catch(Exception e){ 
            logger.error("创建用户海报图片处理异常："+e.getMessage(),e);
        }
        UtilDateTime.countEnd("*************************创建用户海报图片处理完成*************************", startTime); 
        return result;
    } 

    /**
     * 创建用户海报
     * createUserPoster:海报合成方法：二维码和用户头像以及昵称写入海报指定位置. <br/>  
     * 
     * @author luck 
     * @param templateImage
     * @param qrCodeImage
     * @param headImgUrl
     * @param nickName
     * @param json
     * @param outFile
     * @return 
     * @since JDK 1.8
     */
    public boolean createUserPoster(BufferedImage templateImage,BufferedImage qrCodeImage,BufferedImage head,String nickName,JSONObject json,String outFile) {
        boolean result = false;
        if(templateImage==null){
            logger.error("*************************公众号海报文件不存在，不能继续生成海报*************************"); 
            return result;
        }
        if(qrCodeImage==null){
            logger.error("*************************公众号用户二维码图片文件不存在，不能继续生成海报*************************"); 
            return result;
        } 
        long startTime = UtilDateTime.countStart("*************************创建用户海报图片处理开始*************************");
        try{   
            int qrcode_pos_size = 258;
            int qrcode_head_size = 96;
            int qrcode_inner_head_size = 64;
            int qrcode_pos_x = 0;
            int qrcode_pos_y = 0;
            int qrcode_userhead_x = 0;
            int qrcode_userhead_y = 0;
            int qrcode_nickname_x = 0;
            int qrcode_nickname_y = 0;
            int qrcode_nickname_fontsize = 14;
            if(json.containsKey("qrcode_pos_size"))
                qrcode_pos_size = json.getIntValue("qrcode_pos_size");
            if(json.containsKey("qrcode_head_size"))
                qrcode_head_size = json.getIntValue("qrcode_head_size");
            if(json.containsKey("qrcode_inner_head_size"))
                qrcode_inner_head_size = json.getIntValue("qrcode_inner_head_size");
            if(json.containsKey("qrcode_pos_x"))
                qrcode_pos_x = json.getIntValue("qrcode_pos_x");
            if(json.containsKey("qrcode_pos_y"))
                qrcode_pos_y = json.getIntValue("qrcode_pos_y");
            if(qrcode_pos_x<=0 && qrcode_pos_y<=0)
                return result;
            if(json.containsKey("qrcode_userhead_x"))
                qrcode_userhead_x = json.getIntValue("qrcode_userhead_x");
            if(json.containsKey("qrcode_userhead_y"))
                qrcode_userhead_y = json.getIntValue("qrcode_userhead_y");
            if(json.containsKey("qrcode_nickname_x"))
                qrcode_nickname_x = json.getIntValue("qrcode_nickname_x");
            if(json.containsKey("qrcode_nickname_y"))
                qrcode_nickname_y = json.getIntValue("qrcode_nickname_y");
            if(json.containsKey("qrcode_nickname_fontsize"))
                qrcode_nickname_fontsize = json.getIntValue("qrcode_nickname_fontsize"); 
            
            logger.info("二维码大小："+qrcode_pos_size+",内嵌头像大小:"+qrcode_inner_head_size+",头像大小:"+qrcode_head_size); 
            logger.info("模版文件尺寸w："+templateImage.getWidth()+",h:"+templateImage.getHeight()); 
            PicHelper tt = new PicHelper();
            tt.setFont("宋体", qrcode_nickname_fontsize);
            BufferedImage innerHead = tt.resize(head, qrcode_inner_head_size, qrcode_inner_head_size);
            BufferedImage userHead = tt.resize(head, qrcode_head_size, qrcode_head_size);
            logger.info("读取二维码文件尺寸w："+qrCodeImage.getWidth()+",h:"+qrCodeImage.getHeight()); 
            BufferedImage newQRCodeImage = tt.resize(qrCodeImage, qrcode_pos_size, qrcode_pos_size);
            logger.info("重置二维码文件尺寸w："+newQRCodeImage.getWidth()+",h:"+newQRCodeImage.getHeight()); 
            BufferedImage newQRCode = tt.modifyImagetogeter(innerHead,newQRCodeImage,(newQRCodeImage.getWidth()-qrcode_inner_head_size)/2,(newQRCodeImage.getHeight()-qrcode_inner_head_size)/2);
            BufferedImage newTemplate = tt.modifyImagetogeter(newQRCode,templateImage, qrcode_pos_x, qrcode_pos_y);
            if(qrcode_userhead_x>0 && qrcode_userhead_y>0 && userHead!=null)
            {
                newTemplate = tt.modifyImagetogeter(userHead,newTemplate, qrcode_userhead_x, qrcode_userhead_y);
            }
            if(qrcode_nickname_x>0 && qrcode_nickname_y>0 && StringUtil.isNotEmpty(nickName))
            {
                newTemplate = tt.modifyImage(newTemplate, new Object[]{nickName}, qrcode_nickname_x, qrcode_nickname_y,false); 
            }
            logger.info("输出海报文件："+outFile); 
            result = ImageIO.write(newTemplate, "jpg",  new File(outFile));
        }catch(Exception e){ 
            logger.error("创建用户海报图片处理异常："+e.getMessage(),e);
        }
        UtilDateTime.countEnd("*************************创建用户海报图片处理完成*************************", startTime); 
        return result;
    } 

    public BufferedImage getUserHeaderImage(String headimgurl,int size) throws Exception{
        if(StringUtil.isEmpty(headimgurl))return null;
        BufferedImage myAv = null; 
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(headimgurl.substring(0,headimgurl.length()-1)+size);
        HttpResponse response =   httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            if(instream!=null){
                myAv = ImageIO.read(instream);
            }
        } 
        return myAv; 
    } 
}